<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="场景名称">
                <a-input
                  v-model="queryParam.search_key"
                  placeholder="请输入场景名称"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="$refs.table.refresh(true)" type="primary"
                  >查询</a-button
                >
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator flex-y-center flex-x-sb">
        <a-radio-group :value="-1">
          <!-- <a-radio-button :value="-1"> 全部 </a-radio-button> -->
        </a-radio-group>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">添加</a-button>
          <a-popconfirm title="确认删除所选项吗？" @confirm="handleMenuClick">
            <a-button> 批量删除 </a-button>
          </a-popconfirm>
        </div>
      </div>
      <!-- <a-divider /> -->
      <div v-show="selectedRowKeys.length" class="select-title">
        <a-alert
          :message="`已选择 ${selectedRowKeys.length} 项`"
          type="info"
          show-icon
        />
      </div>
      <s-table
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        rowKey="id"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <template slot="name" slot-scope="text, record">
          <div>
            <a-row>
              <a-col :span="22">
                <div style="color: black">{{ record.name }}</div>
              </a-col>
            </a-row>
          </div>
        </template>

        <template slot="pic_url" slot-scope="text, record">
          <div>
            <a-row>
                <a-col :span="2">
                <img
                  :src="record.pic_url"
                  style="width: 50px; height: 50px; border-radius: 5px"
                />
              </a-col>
             
            </a-row>
          </div>
        </template>

        <!-- <a-switch
            slot="status"
            slot-scope="status, record"
            :checked="status > 0"
            @change="onConfirmStatus(record)"
        /> -->
       
        <a-popconfirm
          placement="topLeft"
          slot="status"
          slot-scope="text, record"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onConfirmStatus(record)"
        >
          <template slot="title">
            <p>{{ text == 1 ? '是否确定不显示' : '是否确定显示' }}</p>
          </template>
          <a-switch checked-children="开" un-checked-children="关" :checked="text == 1" />
        </a-popconfirm>

        <a-popconfirm
          placement="topLeft"
          slot="is_default"
          slot-scope="text, record"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onConfirmDefault(record)"
        >
          <template slot="title">
            <p>{{ text == 1 ? '是否取消默认' : '是否设置为默认' }}</p>
          </template>
          <a-switch checked-children="是" un-checked-children="否" :checked="text == 1" />
        </a-popconfirm>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small"
            >编辑</a-button
          >
          <a-divider type="vertical" />
          <a-popconfirm
            title="确认删除该场景吗？"
            @confirm="handleDelete(record)"
          >
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>
      <!-- 添加与编辑 -->
      <a-modal
        :title="isNew ? '创建场景' : '编辑场景'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            style="display: none"
            label="主键"
            hasFeedback
          >
            <a-input
              placeholder="主键"
              :disabled="!isNew"
              v-decorator="['id']"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="场景分类" hasFeedback required>
            <a-cascader
                :options="catList"
                @change="onCascaderChange"
                :fieldNames="{ label: 'cat_name', value: 'id', children: 'children' }"
                placeholder="请选择场景分类分类"
                :value="cat_arr"
            />
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="场景名称"
            hasFeedback
          >
            <a-input
              placeholder="场景名称"
              v-decorator="[
                'name',
                { rules: [{ required: true, message: '请填写场景名称' }] },
              ]"
            />
          </a-form-item>

     
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="场景状态"
          >
            <a-radio-group
              v-decorator="['status', { initialValue: 0 }]"
            >
              <a-radio :value="0"> 禁用 </a-radio>
              <a-radio :value="1"> 启用 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="场景图"
            required
          >
            <cyyUploadImg
              @uploadSuccess="
                (e) => {
                  pic_url = e.data;
                }
              "
              @deleteImg="pic_url = ''"
              :imgSrc="pic_url"
            >
            </cyyUploadImg>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>
  
  <script>
import pick from "lodash.pick";
import { STable } from "@/components";
import {
  save,
  list,
  status,
  del,
  setDefault
} from "@/api/goods/intelligent_scene";
import { list as catList } from '@/api/goods/intelligent_match';
import {  cyyUploadImg } from "@/components/CyyUi/index";

const STATUS = {
  1: "显示",
  0: "不显",
};

const columns = [
  {
    title: "ID",
    width: 120,
    dataIndex: "id",
  },
  {
    title: "名称",
    width: 300,
    dataIndex: "name",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "场景图",
    width: 150,
    dataIndex: "pic_url",
    scopedSlots: { customRender: "pic_url" },
  },
  {
    title: "状态",
    width: 150,
    dataIndex: "status",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "默认",
    width: 150,
    dataIndex: "is_default",
    scopedSlots: { customRender: "is_default" },
  },
  {
    title: "操作",
    width: 80,
    dataIndex: "action",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  name: "IntelligentMatchIndex",
  components: {
    STable,
    cyyUploadImg,
  },
  data() {
    return {
      selectedRowKeys: [],
      isNew: false,
      visible: false,
      pic_url: "",
      cat_id:0,
      cat_arr:[],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: { key: "1", label: "显示" },
      // 查询条件参数
      queryParam: {
        search_key: null,
        search_is_show: null,
      },
      //切换type
      is_mp4: true,
      catList:[],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam);
        return list(parameter).then((res) => {
          return res.data;
        });
      },
      
    };
  },
  filters: {
    statusFilter(key) {
      return STATUS[key];
    },
  },
  created() {
    console.log(this.form);
    catList().then((res) => {
            console.log(res);
          this.catList = res.data.list;
        });
  },
  mounted() {},
  methods: {
    // 选择分类
    onCascaderChange(val) {
      this.cat_id = val[val.length - 1];
      this.cat_arr = val
    },
    // 修改默认场景
    onConfirmDefault(item) {
      const hide = this.$message.loading('请求中...', 0)
      setDefault({
        id: item.id,
        status: item.status
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            this.modalLoading = false
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    // 上下架
    onConfirmStatus(item) {
        console.log(item)
      const hide = this.$message.loading('请求中...', 0)
      status({
        id: item.id,
        status: item.status
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            this.modalLoading = false
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    onSelectChange(val) {
      this.selectedRowKeys = val;
    },
    handleEdit(record) {
      this.isNew = false;
      this.visible = true;
      this.$nextTick(() => {
        record.status = parseInt(record.status)
        this.pic_url = record.pic_url;
        this.cat_id = record.cat_id;
        this.cat_arr = record.cat_id_arr;
        this.form.setFieldsValue(
          pick(record, [
            "name",
            "id",
            "pic_url",
            "cat_id",
            "status"
          ])
        );
        console.log(this.form.getFieldsValue(), 1212121212);
        //this.changeType();
      });
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null,
        search_is_show: null,
      });
      this.$refs.table.refresh(true);
    },
    handleOk(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (err) {
          console.log(err);
          return false;
        }
        if (!this.pic_url) {
            this.$message.error('请上传场景图片！')
            return
        }
        if(this.cat_id == 0){
            this.$message.error('请选择场景分类')
            return
        }
        console.log(values);
        Object.assign(values, {
          pic_url: this.pic_url,
          cat_id:this.cat_id
        });
        this.modalLoading = true;
        save(values)
            .then((res) => {
              console.log(res);
              this.modalLoading = false;
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                });
              } else {
                this.$message.success("场景编辑成功！");
                this.visible = false;
                this.$refs.table.refresh();
              }
            })
            .catch((err) => {
              this.$message.error(err.message);
              this.modalLoading = false;
            });
      });
    },
    onAdd() {
      this.isNew = true;
      this.visible = true;
      this.pic_url = "";
      this.cat_id = 0;
    },
    handleDelete: function (record) {
      const hide = this.$message.loading("删除中...", 0);
      del({
        id: record.id,
      })
        .then((res) => {
          hide();
          if (res.code === 0) {
            this.$message.success("场景删除成功！");
            this.$refs.table.refresh();
          } else {
            this.$error({
              content: res.msg,
            });
          }
        })
        .catch((err) => {
          hide();
          this.$message.error(err.message);
        });
    },
    // 批量操作
    async handleMenuClick() {
      if (!this.selectedRowKeys.length) return;
      try {
        const res = await del({ id: this.selectedRowKeys});
        if (res.code != 0) throw res;
        this.selectedRowKeys = [];
        this.$refs.table.refresh();
        this.$message.success(res.msg);
      } catch (res) {
        this.$message.error(res.msg || "服务器出错");
      }
    },
  },
};
</script>
  
  <style lang="less" scoped>
.over_fid {
  width: 500px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
  